package com.cugmarket.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cugmarket.constant.MessageConstant;
import com.cugmarket.constant.RedisConstants;
import com.cugmarket.dto.UserDTO;
import com.cugmarket.entity.ChatList;
import com.cugmarket.entity.ChatMessage;
import com.cugmarket.entity.ProductInfo;
import com.cugmarket.exception.BaseException;
import com.cugmarket.mapper.ChatListMapper;
import com.cugmarket.mapper.ChatMessageMapper;
import com.cugmarket.service.ChatListService;
import com.cugmarket.service.ChatMessageService;
import com.cugmarket.service.ProductInfoService;
import com.cugmarket.service.UserService;
import com.cugmarket.utils.UserHolder;
import com.cugmarket.vo.ChatListVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import static com.cugmarket.constant.MessageConstant.*;

@Service
@Slf4j
public class ChatListServicelmpl extends ServiceImpl<ChatListMapper, ChatList> implements ChatListService {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private ChatMessageService chatMessageService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ChatMessageMapper chatMessageMapper;  // 用于删除聊天消息


    @Override
    public ChatList create(ChatList chatList) {
        // 从 UserHolder 获取 fromUserId
        String fromUserId = UserHolder.getUser();
        chatList.setFromUserId(fromUserId);

        // 已存在符合条件的 ChatList 记录，则返回
        ChatList existingChatList = lambdaQuery().eq(ChatList::getProductId, chatList.getProductId())
                .and(wrapper -> {
                    wrapper.eq(ChatList::getFromUserId, chatList.getFromUserId())
                            .eq(ChatList::getToUserId, chatList.getToUserId())
                            .or().eq(ChatList::getFromUserId, chatList.getToUserId())
                            .eq(ChatList::getToUserId, chatList.getFromUserId());
                })
                .one();

        if (existingChatList != null) {
            return existingChatList;
        }

        // 获取 ProductInfo 并设置 productImage
        ProductInfo productInfo = productInfoService.getById(chatList.getProductId());
        if (productInfo != null) {
            chatList.setProductImage(productInfo.getImage());
        }

        // 获取 UserDTO 并设置用户昵称和头像
        UserDTO toUser = userService.getUserById(chatList.getToUserId());
        if (toUser != null) {
            chatList.setToUserNick(toUser.getNickName());
            chatList.setToUserAvatar(toUser.getAvatar());
        }

        UserDTO fromUser = userService.getUserById(fromUserId);
        if (fromUser != null) {
            chatList.setFromUserNick(fromUser.getNickName());
            chatList.setFromUserAvatar(fromUser.getAvatar());
        }

        // 保存 ChatList
        boolean save = save(chatList);
        if (!save) {
            throw new BaseException(INSERT_ERROR);
        }
        return chatList;
    }

    /**
     * 根据用户的ID查询所有聊天列表
     * @return
     */
    @Override
    public List<ChatListVo> getMyChatList() {
        // 获取当前用户ID
        String userId = UserHolder.getUser();
        List<ChatList> chatLists = lambdaQuery().eq(ChatList::getFromUserId, userId).or().eq(ChatList::getToUserId, userId)
                .orderByDesc(ChatList::getUpdateTime).list();
        // 获取每个聊天列表的最后一条消息
        ArrayList<ChatListVo> chatListVos = new ArrayList<>();
        for (ChatList chatList : chatLists) {
            ChatListVo vo = getLastMessage(chatList);
            // 获取第一张图片的地址，假设ProductImage字段是逗号分隔的多个URL
            String productImage = chatList.getProductImage();
            if (productImage != null && !productImage.isEmpty()) {
                String[] imgArray = productImage.split(",");
                if (imgArray.length > 0) {
                    vo.setProductImage(imgArray[0].replace("'", ""));  // 去掉单引号
                }
            }
            // 获取未读消息数量
            Integer noReadCount = getNoReadCount(chatList.getId());
            vo.setNoReadCount(noReadCount);
            chatListVos.add(vo);
        }
        return chatListVos;
    }

    @Override
    public int getNoReadTotal() {
        int noReadTotal = 0;
        String userId = UserHolder.getUser();
        List<ChatList> chatLists = lambdaQuery().eq(ChatList::getFromUserId, userId).or().eq(ChatList::getToUserId, userId)
                .orderByDesc(ChatList::getUpdateTime).list();
        for (ChatList chatList : chatLists) {
            int noReadCount = getNoReadCount(chatList.getId());
            noReadTotal += noReadCount;
        }
        return noReadTotal;
    }

    /**
     * 获取聊天列表
     * @param fromUserId
     * @param toUserId
     * @param productId
     * @return
     */
    @Override
    public ChatList getChatListId(String fromUserId, String toUserId, String productId) {
        // 查询符合条件的 ChatList 记录
        ChatList existingChatList = lambdaQuery()
                .eq(ChatList::getProductId, productId)
                .and(wrapper -> wrapper
                        .eq(ChatList::getFromUserId, fromUserId)
                        .eq(ChatList::getToUserId, toUserId)
                        .or()
                        .eq(ChatList::getFromUserId, toUserId)
                        .eq(ChatList::getToUserId, fromUserId)
                )
                .one();
        if (existingChatList != null) {
            // 如果存在旧的chatListId，则返回
            return existingChatList;
        } else {
            // 如果不存在旧的chatListId
            return null;
        }
    }

    @Transactional
    @Override
    public void deleteChatList(String chatListId) {
        // 检查 chatList 是否存在
        ChatList chatList = getById(chatListId);
        if (chatList == null) {
            throw new BaseException(CHAT_LIST_NOT_FOUND);
        }
        chatMessageMapper.deleteByChatListId(chatListId);
        removeById(chatListId);
    }

    /**
     * 获取未读消息数量
     * @param chatListId
     * @return
     */
    private int getNoReadCount(String chatListId) {
        int noRead = 0;
//       // 从Redis中获取消息列表，记录未读消息个数
        ListOperations<String, String> operations = redisTemplate.opsForList();
        List<String> messageList = operations.range(RedisConstants.CHAT_LIST_KEY + chatListId, 0, -1);
        for (String redisMessage : messageList) {
            JSONObject jsonObject = JSON.parseObject(redisMessage);
            if ("0".equals(jsonObject.getString("isRead")) && jsonObject.getString("toUserId").equals(UserHolder.getUser())) {
                noRead += 1;
            }
        }
        // 从数据库中获取消息列表，记录未读消息个数
        List<ChatMessage> list = chatMessageService.lambdaQuery()
                .eq(ChatMessage::getChatListId, chatListId)
                .eq(ChatMessage::getToUserId, UserHolder.getUser())
                .eq(ChatMessage::getIsRead, 0).list();
        noRead += list.size();
        // 返回未读消息数量
        return noRead;
    }

    /**
     * 获取每个聊天列表的最后一条消息
     * @param chatList
     * @return
     */
    private ChatListVo getLastMessage(ChatList chatList) {
        ChatListVo vo = BeanUtil.toBean(chatList, ChatListVo.class);
        ListOperations<String, String> operations = redisTemplate.opsForList();
        List<String> messageList = operations.range(RedisConstants.CHAT_LIST_KEY + chatList.getId(), 0, -1);
        if (!messageList.isEmpty()) {
            // 获取列表的最后一个元素的位置
            int lastIndex = messageList.size() - 1;
            // 使用index方法获取最后一个元素
            String lastMessage = operations.index(RedisConstants.CHAT_LIST_KEY + chatList.getId(), lastIndex);
            ChatMessage chatMessage = convertMessage(lastMessage);
            vo.setChatMessage(chatMessage);
        } else {
            ChatMessage message = chatMessageService.lambdaQuery().eq(ChatMessage::getChatListId, chatList.getId())
                    .orderByDesc(ChatMessage::getSendTime)
                    .last("limit 0,1").one();
            if (BeanUtil.isEmpty(message)) {
                vo.setChatMessage(new ChatMessage());
            } else {
                vo.setChatMessage(message);
            }
        }
        return vo;
    }

    /**
     * 将redis中的消息转换为ChatMessage对象
     * @param message
     * @return
     */
    private ChatMessage convertMessage(String message) {
        ChatMessage chatMessage = new ChatMessage();
        try {
            JSONObject jsonObject = JSON.parseObject(message);
            chatMessage.setChatListId(jsonObject.getString("chatListId"));
            chatMessage.setFromUserId(jsonObject.getString("fromUserId"));
            chatMessage.setFromUserAvatar(jsonObject.getString("fromUserAvatar"));
            chatMessage.setFromUserNick(jsonObject.getString("fromUserNick"));
            chatMessage.setToUserId(jsonObject.getString("toUserId"));
            chatMessage.setToUserAvatar(jsonObject.getString("toUserAvatar"));
            chatMessage.setToUserNick(jsonObject.getString("toUserNick"));
            chatMessage.setContent(jsonObject.getString("content"));
            chatMessage.setIsRead(Integer.parseInt(jsonObject.getString("isRead")));

            // 解析 sendTime
            String sendTimeString = jsonObject.getString("sendTime");
            if (sendTimeString != null && !sendTimeString.isEmpty()) {
                SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
                isoFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // 解析为 UTC 时间
                Date sendTime = isoFormat.parse(sendTimeString);
                chatMessage.setSendTime(sendTime); // 设置到 ChatMessage 中
            } else {
                // 如果 sendTime 为空，则设置为当前时间或其他默认值
                chatMessage.setSendTime(new Date());
            }

        } catch (Exception e) {
            // 捕获解析异常，打印日志或处理错误
            throw new BaseException(e.getMessage());
        }
        return chatMessage;
    }

}
